package com.imgrate.migration.controller;

import com.imgrate.migration.entity.User;
import com.imgrate.migration.repository.UserRepository;
import com.imgrate.migration.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/test")
public class TestController {
    
    private final UserService userService;
    private final UserRepository userRepository;
    private final BCryptPasswordEncoder passwordEncoder;
    
    public TestController(UserService userService, UserRepository userRepository, BCryptPasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }
    
    @GetMapping("/password")
    public Map<String, Object> testPassword() {
        Map<String, Object> result = new HashMap<>();
        
        // 数据库中的哈希值
        String dbHash = "$2a$10$8K1p/a0dhrxiowP.dnkgNORTWgdEDHn5L2/xjpEWuC.QQv4rKO9jO";
        
        // 测试密码
        String testPassword = "admin123";
        
        // 验证密码
        boolean matches = passwordEncoder.matches(testPassword, dbHash);
        
        result.put("passwordMatch", matches);
        result.put("testPassword", testPassword);
        result.put("databaseHash", dbHash);
        
        // 生成新的哈希值用于比较
        String newHash = passwordEncoder.encode(testPassword);
        result.put("newGeneratedHash", newHash);
        
        return result;
    }
    
    @GetMapping("/fix-admin-password")
    public Map<String, Object> fixAdminPassword() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Optional<User> userOpt = userRepository.findByUsername("admin");
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                String correctHash = "$2a$10$8K1p/a0dhrxiowP.dnkgNORTWgdEDHn5L2/xjpEWuC.QQv4rKO9jO";
                
                if (!user.getPassword().equals(correctHash)) {
                    user.setPassword(correctHash);
                    userRepository.save(user);
                    result.put("status", "success");
                    result.put("message", "Admin密码已修复");
                } else {
                    result.put("status", "info");
                    result.put("message", "Admin密码已经是正确的");
                }
                
                result.put("userId", user.getId());
                result.put("username", user.getUsername());
                result.put("currentPasswordHash", user.getPassword());
            } else {
                result.put("status", "error");
                result.put("message", "未找到admin用户");
            }
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "修复密码时出错: " + e.getMessage());
        }
        
        return result;
    }
    
    @GetMapping("/check-admin")
    public Map<String, Object> checkAdmin() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Optional<User> userOpt = userRepository.findByUsername("admin");
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                result.put("found", true);
                result.put("userId", user.getId());
                result.put("username", user.getUsername());
                result.put("email", user.getEmail());
                result.put("fullName", user.getFullName());
                result.put("passwordHash", user.getPassword());
                
                // 验证密码
                String testPassword = "admin123";
                boolean matches = passwordEncoder.matches(testPassword, user.getPassword());
                result.put("passwordMatches", matches);
                
                // 也测试硬编码的哈希值
                String correctHash = "$2a$10$8K1p/a0dhrxiowP.dnkgNORTWgdEDHn5L2/xjpEWuC.QQv4rKO9jO";
                boolean correctMatches = passwordEncoder.matches(testPassword, correctHash);
                result.put("correctHashMatches", correctMatches);
                
                // 检查数据库中的密码是否与预期值匹配
                boolean dbMatchesExpected = user.getPassword().equals(correctHash);
                result.put("dbMatchesExpected", dbMatchesExpected);
            } else {
                result.put("found", false);
                result.put("message", "未找到admin用户");
            }
        } catch (Exception e) {
            result.put("error", "检查admin用户时出错: " + e.getMessage());
        }
        
        return result;
    }
    
    @GetMapping("/debug-password")
    public Map<String, Object> debugPassword() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 测试PasswordEncoder
            String testPassword = "admin123";
            String correctHash = "$2a$10$8K1p/a0dhrxiowP.dnkgNORTWgdEDHn5L2/xjpEWuC.QQv4rKO9jO";
            
            result.put("testPassword", testPassword);
            result.put("correctHash", correctHash);
            
            boolean matches = passwordEncoder.matches(testPassword, correctHash);
            result.put("matches", matches);
            
            // 生成新的哈希进行比较
            String newHash = passwordEncoder.encode(testPassword);
            result.put("newHash", newHash);
            
            boolean newMatches = passwordEncoder.matches(testPassword, newHash);
            result.put("newMatches", newMatches);
            
        } catch (Exception e) {
            result.put("error", "测试PasswordEncoder时出错: " + e.getMessage());
        }
        
        return result;
    }
    
    @GetMapping("/diagnose")
    public Map<String, Object> diagnose() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 检查数据库连接和用户信息
            result.put("databaseCheck", checkDatabaseDirectly());
            
            // 2. 检查PasswordEncoder
            result.put("passwordEncoderCheck", debugPassword());
            
            // 3. 检查通过JPA获取的用户信息
            result.put("jpaCheck", checkAdmin());
            
        } catch (Exception e) {
            result.put("error", "诊断过程中出错: " + e.getMessage());
        }
        
        return result;
    }
    
    private Map<String, Object> checkDatabaseDirectly() {
        Map<String, Object> dbResult = new HashMap<>();
        
        try {
            // 从application配置中获取数据库连接信息
            String url = "jdbc:mysql://localhost:3306/imgrate?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai";
            String username = "root";
            String password = "root";
            
            // 建立连接
            Connection connection = DriverManager.getConnection(url, username, password);
            dbResult.put("connectionSuccess", true);
            
            // 查询admin用户
            String sql = "SELECT id, username, password, email, full_name FROM users WHERE username = ?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, "admin");
            
            ResultSet resultSet = statement.executeQuery();
            
            if (resultSet.next()) {
                dbResult.put("userFound", true);
                dbResult.put("userId", resultSet.getLong("id"));
                dbResult.put("username", resultSet.getString("username"));
                dbResult.put("passwordHash", resultSet.getString("password"));
                dbResult.put("email", resultSet.getString("email"));
                dbResult.put("fullName", resultSet.getString("full_name"));
                
                // 验证密码
                String dbPassword = resultSet.getString("password");
                String testPassword = "admin123";
                String correctHash = "$2a$10$8K1p/a0dhrxiowP.dnkgNORTWgdEDHn5L2/xjpEWuC.QQv4rKO9jO";
                
                boolean matches = passwordEncoder.matches(testPassword, dbPassword);
                dbResult.put("passwordMatches", matches);
                
                boolean expectedMatches = dbPassword.equals(correctHash);
                dbResult.put("expectedHashMatches", expectedMatches);
            } else {
                dbResult.put("userFound", false);
            }
            
            // 关闭资源
            resultSet.close();
            statement.close();
            connection.close();
            
        } catch (Exception e) {
            dbResult.put("connectionSuccess", false);
            dbResult.put("error", e.getMessage());
        }
        
        return dbResult;
    }
}